package com.hns.can.mina.handle;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.hns.can.base.entity.SysUserRoleEntity;
import com.hns.can.base.service.SysUserService;
import com.hns.can.master.entity.BaseEqmtInfoEntity;
import com.hns.can.master.service.EquipmentInfoService;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.enumrate.ReceiveMsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.util.SpringContextUtil;
import com.hns.tool.pub.PubUtil;
/**
 * 实时通讯入口
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class AppHandler extends IoHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AppHandler.class);
    private Map<Long, IoSession> sIdAndSessionMap = new HashMap<Long, IoSession>();
    private Map<String, Long>    userIdAndSIdMap  = new HashMap<String, Long>();
    private Map<Long, String>    sIdAndUserIdMap  = new HashMap<Long, String>();
    
    @Override
    public void messageReceived(IoSession session, Object message) {
        try {
            JSONObject oJson = JSONObject.fromObject(message);
            logger.info("传入的报文：" + oJson.toString() + "!");
            if (PubUtil.isNotEmpty(oJson)) {
                String dataType = oJson.get("type").toString();
                Long sessionId = session.getId();
                SysUserService sysUserService = (SysUserService) SpringContextUtil.getBean("sysUserService");
                if(sysUserService == null){
                    return;
                }
                // 平台连接，保存session
                if (ReceiveMsgType.CLOUD.getFlag().equals(dataType)) {
                    String userId = oJson.get("userId").toString();
                    if (PubUtil.isNotEmpty(userId)) {
                        userIdAndSIdMap.put(userId, sessionId);
                        sIdAndUserIdMap.put(sessionId, userId);
                    } else {
                        throw new BusinessException(MsgType.ERROR.getFlag(), "参数有误!");
                    }
                    // 设备下发，判断并分发报警数据
                } else if (ReceiveMsgType.EQUIPMENT.getFlag().equals(dataType)) {
                    // 给推送报警数据
                    PushMsgService pushMsgService = (PushMsgService) SpringContextUtil.getBean("pushMsgService");
                    if(pushMsgService == null){
                        return;
                    }
                    pushMsgService.pushMsg(userIdAndSIdMap, sIdAndSessionMap, oJson);
                    session.write("接收成功！");
                } 
            }
        } catch (Exception e) {
            session.write("数据有误，接收失败！");
            logger.info("数据有误，接收失败！"+e.getMessage(),e);
            e.printStackTrace();
        }
    }
    
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        super.sessionIdle(session, status);
    }
    
    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        logger.info("发送的消息是：" + message.toString());
    }
    
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        sIdAndSessionMap.put(session.getId(), session);
        super.sessionCreated(session);
    }
    
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        sIdAndSessionMap.remove(session.getId());
        String userId = sIdAndUserIdMap.get(session.getId());
        if(PubUtil.isNotEmpty(userId)){
            userIdAndSIdMap.remove(userId);
        }
        sIdAndUserIdMap.remove(session.getId());
        super.sessionClosed(session);
    }
    
    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
    }
    
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.info("平台数据接收异常捕获异常"+cause.getMessage(), cause);
	}
    
}
